package com.sanshow.charging.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileUtils;
import com.sanshow.charging.R;
import com.youth.banner.Banner;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BatchImageDownload {

    private static String filePath;
    private static List<String> filePaths;
    private static Bitmap mBitmap;
    private static String mSaveMessage = "下载成功";
    private final static String TAG = "ImageActivity";
    private static ImageView imageView;
    private static Banner banner;
    // 成功标识
    private static final int SUCCESS = 200;
    // 失败标识
    private static final int ERROR = 404;
    private static ProgressDialog progressDialog = null;
    //外部存储
    private static String storagePath = "";
    private static Context context = null;


    public static void downLoadImgs(Context activityContext, Banner pBanner, List<String> imgUrlPath) {
        context = activityContext;
        banner = pBanner;
        filePaths = imgUrlPath;
        // getFilesDir()方法用于获取/data/data/<application package>/files目录
        storagePath = context.getFilesDir() + "/sanshow/images/rotation/";

        banner.stopAutoPlay();
        progressDialog = ProgressDialog.show(context, "下载图片", "图片正在下载中，请稍等...", true);
        new Thread(saveFileRunnable).start();
    }

    private static Handler messageHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS:
                    Log.d(TAG, mSaveMessage);
                    Toast.makeText(context, mSaveMessage, Toast.LENGTH_SHORT).show();
                    initBanner();
                    break;
                case ERROR:
                    Toast.makeText(context, "下载失败,请检查原因", Toast.LENGTH_LONG).show();
                    break;
            }

            if (null != progressDialog)
                progressDialog.dismiss();
        }
    };

    private static void initBanner() {

        List<String> list = getAllDataFileName();
        if (list != null && !list.isEmpty()) {
            banner.setImages(list)
                    .setImageLoader(new GlideImageLoader())
                    .start();
        } else {
            List<Integer> localList = new ArrayList<>();
            localList.add(R.mipmap.logo);
            banner.setImages(localList)
                    .setImageLoader(new GlideImageLoader())
                    .start();
        }
    }

    private static Runnable saveFileRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                Looper.prepare();//增加部分
                FileUtils.deleteFilesInDir(storagePath);
                int result = getImageStream();
                if (result == SUCCESS) {
                    Message message = messageHandler.obtainMessage(SUCCESS);
                    message.obj = "success";
                    messageHandler.sendMessage(message);
                } else {
                    Message message = messageHandler.obtainMessage(ERROR);
                    messageHandler.sendMessage(message);
                }
                Looper.loop();//增加部分
            } catch (IOException e) {
                mSaveMessage = "图片保存失败！";
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    };

    /**
     * Get image from newwork
     *
     * @return InputStream
     * @throws Exception
     */
    public static int getImageStream() throws Exception {
        try {
            for (int i = 0; i < filePaths.size() ; i++) {
                // 封装成网络地址
                URL url = new URL(filePaths.get(i));
                // 打开一个连接
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                // 设置连接时长
                httpURLConnection.setConnectTimeout(5000);
                // 设置请求方式
                httpURLConnection.setRequestMethod("GET");
                /**
                 * 注意：⚠️ 不要肤浅的任务 打开连接对象 设置连接时长 设置请求方式 就向服务器发送Http请求了
                 *          是要执行httpURLConnection.getResponseCode()才会向服务器发送Http请求
                 */
                if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    // 得到服务器返回过来的流对象
                    InputStream inputStream = httpURLConnection.getInputStream();
                    mBitmap = BitmapFactory.decodeStream(inputStream);
                    saveFile(mBitmap, i+1);
                } else {
                    return ERROR;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 保存文件
     *
     * @param bm
     * @throws IOException
     */
    public static void saveFile(Bitmap bm, int flag) throws IOException {
        File dirFile = new File(storagePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String mFileName = "ad_image" + flag + ".png";
        File myCaptureFile = new File(storagePath + mFileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
        bos.flush();
        bos.close();
    }

    /**
     * 生成文件夹
     */
    private static File makeDataFile() {
        File file = null;
        try {
            file = new File(storagePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
        return file;
    }

    // 获取目录下的所有文件夹
    public static List<String> getAllDataFileName() {
        // 文件夹路径
        String collectionPath = makeDataFile().getPath();

        List<String> fileList = new ArrayList<>();

        File file = new File(collectionPath);
        File[] tempList = file.listFiles();

        if (tempList != null && tempList.length > 0) {
            for (int i = 0; i < tempList.length; i++) {
                if (tempList[i].isFile()) {
                    // 文件名
                    String filePath = storagePath + tempList[i].getName();
                    fileList.add(filePath);
                }
            }
        }
        return fileList;
    }
}
